import axios from 'axios'
import axiosAdapter from 'axios-miniprogram-adapter'
axios.defaults.adapter = axiosAdapter
export default class Axios {
	#instance = null
	constructor(config) {
		this.#instance = axios.create(config)
		this.#requestInterceptors()
		this.#responseInterceptors()
	}
	#requestInterceptors() {
		this.#instance.interceptors.request.use((request) => {
			if (request.headers) {
				Object.assign(request.headers, {
					token: '',
				})
			}
			console.log('请求拦截器')
			return request
		}, (error) => {
			this.#handleError('请求', error)
		})
	}
	#responseInterceptors() {
		this.#instance.interceptors.response.use((response) => {
			console.log(response, '响应拦截器')
			const res = {
				data: response.data,
				status: response.status
			}
			return res
		}, (error) => {
			this.#handleError('响应', error)
		})
	}
	#handleError(interceptor, error) {
		console.log(interceptor, '出错喽', error)
	}

	async #request(options) {
		console.log(options, 'options')
		try {
			const response = await this.#instance.request(options)
			return response
		} catch (error) {
			//TODO handle the exception
			throw error
		}
	}

	get(config) {
		return this.#request({
			...config,
			method: 'GET'
		})
	}


	post(config) {
		config.data = {
			data: config.data
		}
		return this.#request({
			...config,
			method: "POST"
		})
	}
}